﻿<%@ WebHandler Language="C#" Class="HomeHandler" %>
//Description:MES网站登录相关,代码部署
//Copyright (c) : 通力凯顿（北京）系统集成有限公司
//Writer:Wangjh
//create Date:2021-10-13
using System;
using System.Web;
using System.Collections.Generic;
using System.Web.Script.Serialization;
using System.Linq;
using BusinessRule.Business;
using System.Data;
using Newtonsoft.Json;
using System.IO;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.HSSF.UserModel;
using System.Collections;
using BusinessRule.DTO;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;
using System.Web.SessionState;
using Camstar.WebClient.WebServicesProxy.InSiteWebServices;
using System.ServiceProcess;


public class HomeHandler : IHttpHandler, IRequiresSessionState
{
    private uLMSCommonIBusiness m_CommonObj = uMESBusinessFactory.instance.GetuLMSCommonObject();
    private uLMSUserLoginIBusiness m_UserLoginObject = uMESBusinessFactory.instance.GetuLMSUserLoginObject();
    private uLMSHomeBusiness m_HomeObj = new uLMSHomeBusiness();
         
    public void ProcessRequest(HttpContext context)
    {
        try
        {
            var action = context.Request.Form["action"].ToString();
            switch (action)
            {
                case "GetUserInfo":
                    GetUserInfo(context);
                    break;
                case "JudgeDelay":
                    JudgeDelay(context);
                    break;
                case "logOut":
                    LogOut(context);
                    break;
                case "filterCodeFiles":
                    FilterCodeFiles(context);
                    break;
                case "filterCodeFilesAndDown":
                    FilterCodeFilesAndDown(context);
                    break;
                //Windows服务处理
                case "startService":
                    StartService(context );
                    break;
                case "stopService":
                    StopService(context);
                    break;
                case "resetService":
                    ResetService(context);
                    break;
                default:
                    break;
            }
        }
        catch (Exception e)
        {
            var result = new uMESProcessResult()
            {
                Result = false,
                Message = e.Message
            };
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
    }
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

    #region Windows服务处理

    /// <summary>
    /// 启动服务
    /// </summary>
    /// <param name="serviceName">服务名</param>
    private void StartService(HttpContext context)
    {
        var serviceName = context.Request["serviceName"].ToString();
        ServiceController service = new ServiceController(serviceName);
        if (service.Status == ServiceControllerStatus.Stopped)
        {
            service.Start();
            service.WaitForStatus(ServiceControllerStatus.Running);
            service.Close();
        }
    }

    /// <summary>
    /// 停止服务
    /// </summary>
    /// <param name="serviceName">服务名</param>
    private void StopService(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        uMESProcessResult result = new uMESProcessResult();
        result.Result = false; string msg = "";
        
        var serviceName = context.Request["serviceName"].ToString();
        
        ServiceController service = new ServiceController(serviceName);
        if (service.Status == ServiceControllerStatus.Running)
        {
            service.Stop();
            service.WaitForStatus(ServiceControllerStatus.Stopped);
            service.Close();
        }
        else {
            msg = "此服务未启动，无需停止";
            goto L1;
        }

        result.Result = true; 
        L1: result.Message = msg;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 重启服务
    /// </summary>
    /// <param name="serviceName">服务名</param>
    private void ResetService(HttpContext context)
    {
        var serviceName = context.Request["serviceName"].ToString();
        ServiceController service = new ServiceController(serviceName);
        if (service.Status == ServiceControllerStatus.Running || service.Status == ServiceControllerStatus.Stopped)
        {
            service.Stop();
            service.WaitForStatus(ServiceControllerStatus.Stopped);
            service.Start();
            service.WaitForStatus(ServiceControllerStatus.Running);
            service.Close();
        }
    }

    #endregion



    
    /// <summary>
    /// 登出
    /// </summary>
    /// <param name="context"></param>
    public void LogOut(HttpContext context)
    {
        if (context.Session["CurrentUserInfo"] != null)
        {
            context.Session.Remove("CurrentUserInfo");
        }
        
    }
       
    #region 筛选文件
    /// <summary>
    /// 筛选文件,并下载
    /// </summary>
    /// <param name="context"></param>
    public void FilterCodeFilesAndDown(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        uMESProcessResult result = new uMESProcessResult();
        result.Result = false;

        var topPath = context.Request["topPath"].ToString();//顶层路径 eg:topPath=C:\Program Files (x86)\Camstar\InSite Web Application\InSiteWebApplication\forms\Custom
        string sonPath = context.Request["sonPath"].ToString();//需要筛选的子路径 eg:\my;\Ashx
        string startDate = context.Request["startDate"].ToString();//筛选的开始日期 eg:2022-10-14
        string targetPath = context.Request["targetPath"].ToString();//需要最终放置的路径：eg:C:\Users\Administrator\Desktop\代码部署
        string fileFormat = context.Request["fileFormat"].ToString();//需要筛选的文件类型 eg:vb;cs;aspx;html;htm;js;css
        bool firstDir = bool.Parse(context.Request["firstDir"].ToString());//只筛选本级路径
        if(firstDir)
            sonPath="\\";

        var sonPathList = new List<string>();
        var fileFormatList = new List<string>();

        sonPath = sonPath.Replace("\n", "").Replace("\r", "");
        foreach (string path in sonPath.Split(';'))
        {
            if (string.IsNullOrWhiteSpace(path))
                continue;
            if (!sonPathList.Contains(path))
            {
                sonPathList.Add(path);
            }
        }
        //清除结果文件夹的数据
        var targetDir = new DirectoryInfo(targetPath);
        foreach (DirectoryInfo dr in targetDir.GetDirectories())
        {
            dr.Delete(true);
        }
        foreach (FileInfo fi in targetDir.GetFiles())
        {
            fi.Delete();
        }

        //需要筛选的格式
        foreach (string format in fileFormat.Split(';'))
        {
            if (!fileFormatList.Contains(format))
            {
                fileFormatList.Add(format);
            }
        }

        //追加符合条件的文件
        var resultPathList = new List<string>();
        foreach (string sp in sonPathList)
        {
            DirectoryInfo mydir = new DirectoryInfo(topPath + sp);
            FilterFilesByDate(mydir, sp, targetPath, fileFormatList, DateTime.Parse(startDate).Date, ref resultPathList, firstDir);
        }
        //压缩文件，压缩到InSiteWebApplication\Temp2
        var zip = new ICSharpCode.SharpZipLib.Zip.FastZip();
        var zipFilName = "/Temp2/" + "/代码导出" + (DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalSeconds.ToString() + ".zip";
        zip.CreateZip(HttpContext.Current.Server.MapPath("~" + zipFilName), targetPath, true, "");
                
        result.Result = true;
        result.ReturnData = resultPathList;
        result.Message = zipFilName;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 根据日期，格式，路径 筛选文件出来。用于快速筛选代码部署
    /// </summary>
    /// <param name="context"></param>
    public void FilterCodeFiles(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        uMESProcessResult result = new uMESProcessResult();
        result.Result = false;

        var topPath = context.Request["topPath"].ToString();//顶层路径 eg:topPath=C:\Program Files (x86)\Camstar\InSite Web Application\InSiteWebApplication\forms\Custom
        string sonPath = context.Request["sonPath"].ToString();//需要筛选的子路径 eg:\my;\Ashx
        string startDate = context.Request["startDate"].ToString();//筛选的开始日期 eg:2022-10-14
        string targetPath = context.Request["targetPath"].ToString();//需要最终放置的路径：eg:C:\Users\Administrator\Desktop\代码部署
        string fileFormat = context.Request["fileFormat"].ToString();//需要筛选的文件类型 eg:vb;cs;aspx;html;htm;js;css
        bool  firstDir =bool.Parse ( context.Request["firstDir"].ToString());//只筛选本级路径
        if (firstDir)
            sonPath = "\\";
        
        var sonPathList = new List<string>();
        var fileFormatList = new List<string>();

        sonPath = sonPath.Replace("\n", "").Replace("\r", "");
        foreach (string path in sonPath.Split(';'))
        {
            if (string.IsNullOrWhiteSpace(path))
                continue;
            if (!sonPathList.Contains(path))
            {
                sonPathList.Add(path);
            }
        }
        //清除结果文件夹的数据
        var targetDir = new DirectoryInfo(targetPath);
        foreach (DirectoryInfo dr in targetDir.GetDirectories())
        {
            dr.Delete(true);
        }
        foreach (FileInfo fi in targetDir.GetFiles())
        {
            fi.Delete();
        }

        //需要筛选的格式
        foreach (string format in fileFormat.Split(';'))
        {
            if (!fileFormatList.Contains(format))
            {
                fileFormatList.Add(format);
            }
        }

        //追加符合条件的文件
        var resultPathList = new List<string>();
        foreach (string sp in sonPathList)
        {
            DirectoryInfo mydir = new DirectoryInfo(topPath + sp);
            FilterFilesByDate(mydir, sp, targetPath, fileFormatList, DateTime.Parse(startDate).Date, ref resultPathList, firstDir);
        }

        result.Result = true;
        result.ReturnData = resultPathList;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 筛选文件，有递归
    /// </summary>
    /// <param name="sourcePath"></param>
    /// <param name="targetPath"></param>
    /// <param name="startDate"></param>
    void FilterFilesByDate(DirectoryInfo sourceDir, string sonPathItem, string targetPath, List<string> fileFormat, DateTime startDate, ref List<string> resultPath, Boolean firstDir=false)
    {
        foreach (FileInfo fi in sourceDir.GetFiles())
        {
            if ((fileFormat.Contains(fi.Extension.Replace(".", ""))||fileFormat .Contains ("*")) && fi.LastWriteTime >= startDate)
            {
                if (!Directory.Exists(targetPath + sonPathItem))
                {
                    Directory.CreateDirectory(targetPath + sonPathItem);
                }
                File.Copy(fi.FullName, targetPath + sonPathItem + "\\" + fi.Name, true);
                resultPath.Add(targetPath + sonPathItem + "\\" + fi.Name);
            }
        }
        if (firstDir)
            return;
        foreach (DirectoryInfo dr in sourceDir.GetDirectories())
        {
            string sonDirName = dr.FullName.Replace(sourceDir.FullName, "");
            FilterFilesByDate(dr, sonPathItem + sonDirName, targetPath, fileFormat, startDate, ref resultPath);
        }
    }
#endregion

    
    
      /// <summary>
    /// 判断是否超期
    /// </summary>
    /// <param name="context"></param>
    public void JudgeDelay(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        uMESProcessResult result = new uMESProcessResult();
        result.Result = false;

        if (context.Session["CurrentUserInfo"] != null)
        {
            result.Result = true;
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
        
    }

    /// <summary>
    /// 查询获取列表
    /// </summary>
    /// <param name="context"></param>
    public void GetUserInfo(HttpContext context)
    {
        Dictionary<string, string> para = new Dictionary<string, string>();
        para.Add("EmployeeName", context.Request.Form["EmployeeName"].ToString());//
        
        //返回对象
        var result =new Dictionary<string, object>();
        //如果已经存在用户给出提示
        if (context.Session["CurrentUserInfo"] != null)
        {
            CurrentUserInfo tempUserInfo = context.Session["CurrentUserInfo"] as CurrentUserInfo;
            if (tempUserInfo.EmployeeName != context.Request.Form["EmployeeName"].ToString())
            {
                result.Add("userInfo", null);
                result.Add("message", "此会话已有登录人员：" + tempUserInfo.FullName+",请退出此用户后再登陆！" );
                context.Response.Write(JsonConvert.SerializeObject(result));
                return;
            }
        }
        //获取sessionID
        var sessionID = "";
        EncryptedField EncryptedField=new EncryptedField();
        if (context.Session["SessionID"] == null)
        {
            if (context.Application.Contents["T_SessionID"] == null)
            {

            }
            else {
                EncryptedField = (EncryptedField)context.Application.Contents["T_SessionID"];
            }
        }
        else {
            EncryptedField = (EncryptedField)context.Session["SessionID"];
        }
        sessionID = EncryptedField.Value;
        //用户信息
        CurrentUserInfo userInfo = m_CommonObj.GetUserInfo(para["EmployeeName"], sessionID);
        string strCurrentInfo = "", strReportURL="";
        if (userInfo.EmployeeName != null)
        {
            string apiName="", apiPassword = "";
            m_UserLoginObject.GetDomainUser(userInfo.Factory, ref apiName, ref apiPassword);
            userInfo.APIUserName = apiName;
            userInfo.APIPassword = apiPassword;

            context.Session["CurrentUserInfo"] = userInfo;
            context.Session.Timeout = 20;

            strCurrentInfo = String.Format("版本号：5.9.0.1&nbsp&nbsp&nbsp&nbsp{0} {1} ", userInfo.FullName, userInfo.OrgInfo);
            strReportURL = String.Format("http://localhost/MESReport/Login.aspx?giLoginUserName={0}&pwd={1}", userInfo.EmployeeName, userInfo.Password );

            result.Add("userInfo", userInfo);
            //菜单信息
            var menuInfo = m_HomeObj.GetMenuInfoByUser(para["EmployeeName"]);
            result.Add("menuInfo", menuInfo); result.Add("strCurrentInfo", strCurrentInfo);
        }
        else {
            result.Add("userInfo", null);
        }
        
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    

}